package com.gzh.core.util;

import com.auth0.jwt.JWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class RequestContextUtil {

  public static HttpServletRequest getRequest(){
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (null == requestAttributes){
      return null;
    }
    return requestAttributes.getRequest();
  }

  public static Integer getCurrentUserId(){
    HttpServletRequest request = getRequest();
    // 从 http 请求头中取出 token
    String token = request.getHeader("token");
    String userId = JWT.decode(token).getClaim("userId").asString();
    return NumericHelper.toInteger(userId);
  }
}
